package com.xiongjie.humanTask.service;

import com.xiongjie.humanTask.entity.TaskEntity;
import io.reactiverse.pgclient.*;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;

import java.util.ArrayList;
import java.util.List;

public class PgService {

    PgPool client;

    public PgService(Vertx vertx) {
        PgPoolOptions options = new PgPoolOptions()
                .setPort(5432)
                .setHost("localhost")
                .setDatabase("human")
                .setUser("postgres")
                .setPassword("postgres")
                .setMaxSize(5);
        client = PgClient.pool(vertx,options);
    }

    public void save(TaskEntity entity) {
        List<Tuple> batch = new ArrayList<>();
        batch.add(
                Tuple.of(entity.getKey(),
                entity.getVariables(),
                entity.getTimestamp(),
                entity.getName(),
                entity.getDescription(),
                entity.getFormFields(),
                entity.getTaskForm(),
                entity.getAssignee(),
                entity.getCandidateGroup(),
                "执行中"
        ));

        client.preparedBatch("INSERT INTO task (key, variables,timestamp,name,description,formFields,taskForm,assignee,candidateGroup,state) VALUES ($1, $2,$3,$4,$5,$6,$7,$8,$9,$10)",batch,res -> {
            if (res.succeeded()) {
                System.out.println(entity.getKey()+"任务插入成功");
            } else {
                System.out.println("Batch insert failed " + res.cause());
            }
        });
    }

    public Future<TaskEntity> findById(long jobkey) {
        Promise promise= Promise.promise();
        client.preparedQuery("SELECT * from task WHERE key=$1 and state='执行中'", Tuple.of(jobkey),  ar -> {
            if (ar.succeeded()) {
                PgRowSet rows = ar.result();
                System.out.println(jobkey+"任务查询成功");

                Row row=rows.iterator().next();
                TaskEntity taskEntity=new TaskEntity();
                taskEntity.setKey(jobkey);
                taskEntity.setVariables(row.getString("variables"));
                taskEntity.setTimestamp(row.getLong("timestamp"));
                taskEntity.setName(row.getString("name"));
                taskEntity.setDescription(row.getString("description"));
                taskEntity.setFormFields(row.getString("formFields"));
                taskEntity.setTaskForm(row.getString("taskForm"));
                taskEntity.setAssignee(row.getString("candidateGroup"));
                taskEntity.setCandidateGroup(row.getString("key"));
                taskEntity.setState("执行中");

                promise.complete(taskEntity);
            } else {
                System.out.println("Failure: " + ar.cause().getMessage());
                promise.fail("Failure: " + ar.cause().getMessage());
            }
        });
        return promise.future();
    }

    public void updateState(TaskEntity entity) {
        List<Tuple> batch = new ArrayList<>();
        batch.add(Tuple.of(entity.getKey()));

        client.preparedBatch("update task set state='任务完成' where key=$1 and state='执行中'",batch,res -> {
            if (res.succeeded()) {
                System.out.println(entity.getKey()+"任务执行成功");
            } else {
                System.out.println("Batch update failed " + res.cause());
            }
        });
    }
}
